package com.example.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 咔咔吃萝卜 on 2017/5/17.
 */

public class CityActivity extends AppCompatActivity {
    private MyAdapter myAdapter;
    private String[] areaIds = {"1","1","1","1","1"};
    private Button deleteButton;
    private ListView listView;
    private SimpleAdapter simpleAdapter;
    private String[] cities = {"北京 朝阳", "江苏 宿迁", "江苏 南京", "江苏 徐州", "辽宁 朝阳"};
    private List<Map<String, Object>> listems = new ArrayList<Map<String, Object>>();
    private DBHelper dbHelper;
    private String[] name, ids;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_layout);

        /*生成一个Map组成的list*/
        for (int i = 0; i < cities.length; i++) {
            Map<String, Object> listem = new HashMap<String, Object>();
            listem.put("name", cities[i]);
            listems.add(listem);
        }
        listView = (ListView) findViewById(R.id.city_listview);
        deleteButton = (Button) findViewById(R.id.delete_city_button);
        myAdapter = new MyAdapter(cities,areaIds,deleteButton);
        listView.setAdapter(myAdapter);
        dbHelper = DBHelper.getInstance(this);
        changeAdapter(dbHelper.queryAllCities());





       /*设置适配器，填充数据*/
        /**
         * SimpleAdapter并不Simple，可以用SimpleAdapter做出很多样式的ListView
         * 参数介绍：context　　SimpleAdapter关联的View的运行环境
         * data　　　 一个Map组成的List。在列表中的每个条目对应列表中的一行,每一个map中应该包含所有在from参数中指定的键
         * resource    一个定义列表项的布局文件的资源ID。布局文件将至少应包含那些在to中定义了的ID
         * from          一个将被添加到Map映射上的键名
         * to　　　　 将绑定数据的视图的ID,跟from参数对应,这些应该全是TextView
         */

        //点击事件——返回主页、并且更换显示当地的天气
        //不能直接对ListView做click处理，应该是做Itemclick处理
//        listView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.setClass(CityActivity.this, MainActivity.class);
//                CityActivity.this.startActivity(intent);
//            }
//        });

//        simpleAdapter = new SimpleAdapter(getApplication(), listems,
//                R.layout.activity_search_listview_item, new String[]{"name"},
//                new int[]{R.id.result_text});
//        listView.setAdapter(simpleAdapter);


//        点击事件——返回主页、并且更换显示当地的天气
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = getIntent();
                Bundle bundle = new Bundle();
                bundle.putString("cityname", name[position]);
                intent.putExtras(bundle);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        //添加
        Button button = (Button) findViewById(R.id.add_city_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CityActivity.this, SerachActivity.class);
                startActivityForResult(intent,0);
                //startActivity(intent);
            }
        });

        //删除

        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] result = myAdapter.getCheckedCities();
                for(int i=0; i<result.length; i++){
                    dbHelper.deleteDataById(Integer.parseInt(result[i]));
                }
                changeAdapter(dbHelper.queryAllCities());
            }
        });



    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            dbHelper.insertData(new String[]{"cityname"},
                    new String[]{bundle.getString("city")});
            changeAdapter(dbHelper.queryAllCities());
        }
    }


    private void changeAdapter(List<Map<String, Object>> list){
        ids = new String[list.size()];
        name = new String[list.size()];
        for(int i=0;i<list.size();i++){
            ids[i] = list.get(i).get("id").toString();
            name[i] = list.get(i).get("cityname").toString();
        }
        myAdapter = new MyAdapter(name, ids, deleteButton);
        listView.setAdapter(myAdapter);
    }


    private class MyAdapter extends BaseAdapter{

        //返回该适配器中有多少条目
        @Override
        public int getCount() {
            return cities.length;
        }

//        根本位置返回该位置的内容
        @Override
        public Object getItem(int position) {
            return position;
        }

//        返回每个条目的ID，一般都返回位置索引
        @Override
        public long getItemId(int position) {
            return position;
        }

//        返回条目的样式
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewSet viewSet = null;
            //convertView相当于一个缓存，当他为空，代表尚未被缓存
            if(convertView == null)
            {
                viewSet = new ViewSet();
//                将xml转换为view
                convertView = LayoutInflater.from(getApplication()).inflate(R.layout.activity_city_listview_item,parent,false);
                viewSet.textView = (TextView) convertView.findViewById(R.id.listview_item_textview);
                viewSet.checkBox = (CheckBox) convertView.findViewById(R.id.listview_item_checkbox);
                convertView.setTag(viewSet);
            }else{
                //已经缓存好了，直接取
                viewSet = (ViewSet) convertView.getTag();
            }
            viewSet.textView.setText(cities[position]);
            //状态改变监听器，当被选择时，更新chencedNum和checkedArray
            viewSet.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if (isChecked) {
                        checkedArray[position] = true;
                        checkedNum++;
                        if (checkedNum == 1) {
                            button.setEnabled(true);
                        }
                    } else {
                        checkedArray[position] = false;
                        checkedNum--;
                        if (checkedNum == 0) {
                            button.setEnabled(false);
                        }
                    }
                }
            });
            return convertView;


        }

        private class ViewSet{
            //文字部分
            TextView textView;
            //复选框部分
            CheckBox checkBox;
        }

        private String[] cities;
        private int checkedNum = 0;
        private Button button;
        private boolean[] checkedArray;
        private String[] cityIds;

        public MyAdapter(String[] cities, String[] cityIds, Button button){
            //城市名称，城市ID，删除按钮，初始状态
            this.cities=cities;
            this.button=button;
            this.cityIds=cityIds;
            this.checkedArray=new boolean[cities.length];
            //每个城市初始时都是未被选择的
            for (int i =0;i<cities.length;i++)
            {
                this.checkedArray[i]=false;
            }
        }

        //返回选择的城市代码
        public String[] getCheckedCities(){
            List<String> checkedCityIdList = new ArrayList<String>();
            for(int i=0;i<checkedArray.length;i++){
                if(checkedArray[i] == true){
                    checkedCityIdList.add(cityIds[i]);
                }
            }
            String[] checkedCityIdArray = new String[checkedCityIdList.size()];
            return checkedCityIdList.toArray(checkedCityIdArray);
        }

    }

}
